package com.example.Hongbao;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.graphics.drawable.AnimationDrawable;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.*;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Fcy on 2015/11/26.
 */
public class WindowAccessibilitySeivice extends AccessibilityService {
	// 可以是多个，xml中逗号隔开
	// String installPackge[] = { "org.jaaksi.test" };

	@Override
	protected void onServiceConnected() {
		super.onServiceConnected();
		// 可用代码配置当前Service的信息
		// AccessibilityServiceInfo info = new AccessibilityServiceInfo();
		// info.packageNames = installPackge; //监听过滤的包名
		// info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK; //监听哪些行为
		// info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN; //反馈
		// info.notificationTimeout = 100; //通知的时间
		// setServiceInfo(info);
	}

	/**
	 * 会在什么时候回调
	 *
	 * @param event
	 */
	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		Log.i("fcy", "----------------- onAccessibilityEvent");
		// 下面每行代码都会执行
		if (event.getSource() != null && MyApplication.getInstance().isOpen) {
//			if (!FileUtils.isUpdateExists()) {
//				MyApplication.getInstance().isOpen = false;
//				// 关闭弹窗
//				MyWindowManager.removeWindow(this);
//				return;
//			}

			// 点击抢红包
			findAndPerformId(event, "com.android.updater:id/more_btn");
			// 点击手动选择安装包
			findAndPerformAction("手动选择安装包");
			// 找到ListView并进行滑动
			findItemPerformAction(ConstantsUtil.UPDATE_FILE_NAME);
//
			findList();
//			// ---------- 等待安装
//			// 重启系统
//			findAndPerformAction("立即重启");

		}
	}


	@Override
	public void onInterrupt() {

	}

	/**
	 * 通过id查找
	 *
	 * @param event
	 * @param id
	 */
	private void findAndPerformId(AccessibilityEvent event, String id) {
		// AccessibilityNodeInfo nodeInfo = event.getSource();
		AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
		if (nodeInfo == null)
			return;
		List<AccessibilityNodeInfo> nodes = nodeInfo
			.findAccessibilityNodeInfosByViewId(id);

		for (int i = 0; i < nodes.size(); i++) {
			AccessibilityNodeInfo node = nodes.get(i);
			// 执行按钮点击行为
			if (node.isEnabled()) {
				node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
			}
			// if (node.getClassName().equals("android.widget.ImageView")
			// && node.isEnabled())
			// {
			// node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
			// }
		}
		// nodeInfo.recycle();
	}

	private void findList() {
		// 查找当前窗口中包含“text”文字的按钮
		AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
		if (nodeInfo == null)
			return;
		// 通过文字找到当前的节点
		List<AccessibilityNodeInfo> nodes = nodeInfo
			.findAccessibilityNodeInfosByText(":"); // 找 :

		if (!nodes.isEmpty()) { // ListView
			final AccessibilityNodeInfo list = nodes.get(0).getParent()
				.getParent();
			// 每隔100ms执行一次滚动（如何让滚动到最后了不在滚动）
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					// if (list.isScrollable())
					list.performAction(
						AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
				}
			}, 0, 300);
		}

	}

	@SuppressLint("NewApi")
	private void findAndPerformAction(String text) {
		// 查找当前窗口中包含“text”文字的按钮
		AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
		if (nodeInfo == null)
			return;
		// 通过文字找到当前的节点
		List<AccessibilityNodeInfo> nodes = nodeInfo
			.findAccessibilityNodeInfosByText(text);

		for (int i = 0; i < nodes.size(); i++) {
			AccessibilityNodeInfo node = nodes.get(i);
			// 执行按钮点击行为
			if (node.isEnabled()) {
				node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
			}
			// if (node.getClassName().equals("android.widget.Button")
			// && node.isEnabled())
			// {
			// node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
			// }
		}
		nodeInfo.recycle();
	}

	/**
	 * 点击找到的text所在的item
	 *
	 * @param text
	 */
	private void findItemPerformAction(String text) {
		// 查找当前窗口中包含“text”文字的按钮
		AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
		if (nodeInfo == null)
			return;
		List<AccessibilityNodeInfo> nodes = nodeInfo
			.findAccessibilityNodeInfosByText(text);

		for (int i = 0; i < nodes.size(); i++) {
			AccessibilityNodeInfo node = nodes.get(i);
			// 执行按钮点击行为
			if (node.isEnabled()) {
				node.getParent()
					.performAction(AccessibilityNodeInfo.ACTION_CLICK);
			}
		}

	}

}
